﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Caching;

using C = System.Web.Caching;

namespace Caching
{
    public class CollaborationCacheItem : CacheBaseItem
    {
        private const string CacheCorporationIdPrefix = "DependCId_";
        private static Dictionary<Guid, object> _cachedCorporationIds = new Dictionary<Guid, object>();

        public Guid CorporationId
        {
            get;
            set;
        }

        public CollaborationCacheItem(Guid corporationId, string key1, Guid key2)
            : this(corporationId, key1 + "_" + key2.ToString("N"), null, CacheManager.NoAbsoluteExpiration, C.Cache.NoSlidingExpiration, PriorityLevel.Normal, null)
        {
        }

        public CollaborationCacheItem(Guid corporationId, string key)
            : this(corporationId, key, null, CacheManager.NoAbsoluteExpiration, C.Cache.NoSlidingExpiration, PriorityLevel.Normal, null)
        {
        }

        public CollaborationCacheItem(Guid corporationId, string key, double minutesBeforeExpiration)
            : this(corporationId, key, null, DateTime.Now.AddMinutes(minutesBeforeExpiration),C.Cache.NoSlidingExpiration, PriorityLevel.Normal, null)
        {
        }

        public CollaborationCacheItem(Guid corporationId,int dbIndex, string key, double minutesBeforeExpiration)
         : this(corporationId, key, null, DateTime.Now.AddMinutes(minutesBeforeExpiration),TimeSpan.FromMinutes(minutesBeforeExpiration), (PriorityLevel)dbIndex, null)
        {
        }



        public CollaborationCacheItem(
            Guid corporationId,
            string key,
            CacheItemBaseDependency[] dependencies,
            DateTime absoluteExpiration,
            TimeSpan slidingExpiration,
            PriorityLevel priority,
            CacheRemovedCallback onRemoveCallback)
            : base(corporationId.ToString("N") + "_" + key, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback)
        {
            this.CorporationId = corporationId;
        }


        public override void OnBeingAddedIntoCache()
        {
            if (CorporationId == Guid.Empty)
            {
                return;
            }

            string cacheKey = GetDependencyCorporationIdCacheKey(CorporationId);

            // If the dependency CorporationId does not exist in cache, add it.
            lock (_cachedCorporationIds)
            {
                if (!_cachedCorporationIds.ContainsKey(CorporationId))
                {
                    CacheManager.Add(
                                     new CacheBaseItem(
                                                       cacheKey,
                                                       null,
                                                       C.Cache.NoAbsoluteExpiration,
                                                       C.Cache.NoSlidingExpiration,
                                                       PriorityLevel.High,
                                                       Cache_RemovedCallback),
                                     CorporationId);
                    _cachedCorporationIds.Add(CorporationId, null);
                }
            }

            var dependencies = this.Dependencies != null ? new List<CacheItemBaseDependency>(this.Dependencies) : new List<CacheItemBaseDependency>();
            var keysDependency = (from d in dependencies
                                  where d is CacheItemKeysDependency
                                  select (d as CacheItemKeysDependency)).FirstOrDefault();
            if (keysDependency == null)
            {
                keysDependency = new CacheItemKeysDependency();
                dependencies.Add(keysDependency);
            }
            var keys = new List<string>();
            if (keysDependency.Keys != null)
            {
                keys.AddRange(keysDependency.Keys);
            }
            keys.Add(cacheKey);
            keysDependency.Keys = keys.ToArray();

            this.Dependencies = dependencies.ToArray();
        }

        private static string GetDependencyCorporationIdCacheKey(Guid corporationId)
        {
            return CacheCorporationIdPrefix + corporationId.ToString("N");
        }

        private static void Cache_RemovedCallback(string key, object value, CacheRemovedReason reason)
        {
            Guid corporationId = Guid.ParseExact(key.Substring(CacheCorporationIdPrefix.Length), "N");

            lock (_cachedCorporationIds)
            {
                _cachedCorporationIds.Remove(corporationId);
            }
        }

        public static void ClearCorporationCache(Guid corporationId)
        {
            CacheManager.Remove(GetDependencyCorporationIdCacheKey(corporationId));
        }

        public static void ClearAllCorporationCache()
        {
            // Create a new list to avoid modify _cachedCorporationIds while enumrating.
            // (Cache_RemovedCallback() will modify the _cachedCorporationIds)
            lock (_cachedCorporationIds)
            {
                List<Guid> corporationIds = new List<Guid>(_cachedCorporationIds.Keys);
                foreach(Guid corporationId in corporationIds)
                {
                    ClearCorporationCache(corporationId);
                }
            }
        }

    }

}
